package com.crp.unitalinforbaseplat.app.unitalinforbaseplat.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.crp.unitalinforbaseplat.app.core.BaseController;
import com.crp.unitalinforbaseplat.app.core.Message;
import com.crp.unitalinforbaseplat.app.core.MessageUtil;
import com.crp.unitalinforbaseplat.app.core.utils.EmptyUtils;
import com.crp.unitalinforbaseplat.app.unitalinforbaseplat.entity.*;
import com.crp.unitalinforbaseplat.app.unitalinforbaseplat.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsx
 * @since 2020-04-21
 */
@RestController
@RequestMapping("/inventory")
public class InventoryController extends BaseController {
    @Autowired
    IInventoryReportService inventoryReportService;
    @Autowired
    IInventoryService inventoryService;
    @Autowired
    IPartsService partsService;
    @Autowired
    IEnterStoreService enterStoreService;
    @Autowired
    IExitStoreService exitStoreService;
    @Autowired
    IStoreService storeService;
    @RequestMapping("/list_index")
    ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView("backend/unitalinforbaseplat/inventoryReport/list");
        modelAndView.addObject("roleName",getRoleName());
        return modelAndView;
    }
    @RequestMapping("/add_index")
    ModelAndView addIndex(Inventory inventory) {
        if(!EmptyUtils.isEmpty(inventory.getId())){
            ModelAndView modelAndView = new ModelAndView("backend/unitalinforbaseplat/inventoryReport/update");
            modelAndView.addObject("roleName",getRoleName());
            modelAndView.addObject("enterStoreList",inventoryReportService.list(new LambdaQueryWrapper<InventoryReport>().eq(InventoryReport::getInventoryId,inventory.getId())));
            modelAndView.addObject("inventoryId",inventory.getId());
            return modelAndView;
        }else{
            List<EnterStore> enterStoreList = enterStoreService.listGroupByPartsId();
            ModelAndView modelAndView = new ModelAndView("backend/unitalinforbaseplat/inventoryReport/add");
            modelAndView.addObject("roleName",getRoleName());
            modelAndView.addObject("enterStoreList",enterStoreList);
            return modelAndView;
        }
    }


    @RequestMapping("/review_index")
    ModelAndView reviewIndex(Inventory inventory) {
        ModelAndView modelAndView = new ModelAndView("backend/unitalinforbaseplat/inventoryReport/review");
        modelAndView.addObject("roleName",getRoleName());
        modelAndView.addObject("enterStoreList",inventoryReportService.list(new LambdaQueryWrapper<InventoryReport>().eq(InventoryReport::getInventoryId,inventory.getId())));
        modelAndView.addObject("inventoryId",inventory.getId());
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("/list")
    PageBean<Inventory> index(Inventory inventory) {
        PageBean<Inventory> pageBean = new PageBean<Inventory>();
        List<Inventory> inventoryList = inventoryService.list(new LambdaQueryWrapper<Inventory>().like(StringUtils.isNotBlank(inventory.getName()),Inventory::getName,inventory.getName()));
        pageBean.setData(inventoryList);
        return pageBean;
    }

    @ResponseBody
    @RequestMapping("/delete")
    Message delete(Inventory inventory) {
        inventoryService.removeById(inventory.getId());
        return MessageUtil.createMessage(true,"删除成功");
    }

    @ResponseBody
    @RequestMapping("/add")
    Message add(@RequestParam("ids") Integer[] ids,@RequestParam("nums")Integer[] nums) {
        if(ids.length == 0 || nums.length == 0 || ids.length != nums.length){
            return MessageUtil.createMessage(false,"请完善信息");
        }
        // 首先生成报表目录
        Inventory inventory = new Inventory();
        inventory.setCreateTime(new Date());
        inventory.setCreateUserId(getId().intValue());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日") ; //使用了默认的格式创建了一个日期格式化对象。
        String time = dateFormat.format(new Date()); //可以把日期转换转指定格式的字符串
        inventory.setName(time+"零配件盘点");
        inventory.setDescs(time+"零配件盘点");
        inventory.setStatus(1);
        inventoryService.save(inventory);
        List<EnterStore> enterStoreList = enterStoreService.listGroupByPartsId();
        List<EnterStore> addEnterList = new ArrayList<>();
        List<ExitStore> addExitList = new ArrayList<>();
        if(EmptyUtils.isAllEmpty(enterStoreList)){
            return MessageUtil.createMessage(false,"无入库记录");
        }
        for (int i=0;i<ids.length;i++) {
            for (EnterStore enterStore : enterStoreList) {
                if(enterStore.getId() == ids[i]){
                    // 生成报表
                    InventoryReport inventoryReport = new InventoryReport();
                    inventoryReport.setCreateTime(new Date());
                    inventoryReport.setCreateUserId(getId().intValue());
                    inventoryReport.setName(enterStore.getName());
                    inventoryReport.setSpecifications(enterStore.getSpecifications());
                    inventoryReport.setModel(enterStore.getModel());
                    inventoryReport.setManufacturer(enterStore.getManufacturer());
                    inventoryReport.setNum(enterStore.getNum());
                    inventoryReport.setInventoryTime(new Date());
                    inventoryReport.setApplicationName(getUserName());
                    inventoryReport.setPartsId(enterStore.getPartsId());
                    inventoryReport.setInventoryId(inventory.getId());
                    inventoryReport.setPeopleNum(nums[i]);
                    inventoryReport.setStoreId(enterStore.getStoreId());
                    inventoryReport.setStoreName(enterStore.getStoreName());
                    inventoryReportService.save(inventoryReport);

                    //判断盘盈盘亏发起出库入库申请
                    if(inventoryReport.getNum() > inventoryReport.getPeopleNum()){
                        // 库存数大于人工报表数   损耗
                        ExitStore exitStore = new ExitStore();
                        exitStore.setName(enterStore.getName());
                        exitStore.setNum(inventoryReport.getNum()-inventoryReport.getPeopleNum());
                        exitStore.setSpecifications(enterStore.getSpecifications());
                        exitStore.setModel(enterStore.getModel());
                        exitStore.setManufacturer(enterStore.getManufacturer());
                        exitStore.setStoreName(enterStore.getStoreName());
                        exitStore.setStoreId(enterStore.getStoreId());
                        exitStore.setPartsId(enterStore.getPartsId());
                        exitStore.setType(2);
                        exitStore.setApplicationName(getUserName());
                        exitStore.setCreateTime(new Date());
                        exitStore.setFindTime(new Date());
                        exitStore.setInventoryId(inventory.getId());
                        exitStore.setValidityTime(enterStore.getValidityTime());
                        exitStore.setEnterTime(enterStore.getEnterTime());
                        exitStore.setExitTime(new Date());
                        exitStore.setCreateUserId(getId().intValue());
                        exitStore.setStatus(1);
                        addExitList.add(exitStore);
                    }else if(inventoryReport.getNum().equals(inventoryReport.getPeopleNum())){
                        // 无误无需发起任何任期
                    }else if(inventoryReport.getNum() < inventoryReport.getPeopleNum()){
                        // 库存数小于人工报表数  发起盘盈入库
                        EnterStore enterStore1 = new EnterStore();
                        enterStore1.setName(enterStore.getName());
                        enterStore1.setNum(inventoryReport.getPeopleNum()-inventoryReport.getNum());
                        enterStore1.setSpecifications(enterStore.getSpecifications());
                        enterStore1.setModel(enterStore.getModel());
                        enterStore1.setManufacturer(enterStore.getManufacturer());
                        enterStore1.setStoreName(enterStore.getStoreName());
                        enterStore1.setStoreId(enterStore.getStoreId());
                        enterStore1.setPartsId(enterStore.getPartsId());
                        enterStore1.setApplicationName(getUserName());
                        enterStore1.setCreateTime(new Date());
                        enterStore1.setInventoryId(inventory.getId());
                        enterStore1.setValidityTime(enterStore.getValidityTime());
                        enterStore1.setEnterTime(new Date());
                        enterStore1.setCreateUserId(getId().intValue());
                        enterStore1.setStatus(1);
                        addEnterList.add(enterStore1);
                    }
                }
            }

        }
        if(!EmptyUtils.isAllEmpty(addEnterList)){
            enterStoreService.saveBatch(addEnterList);
        }
        if(!EmptyUtils.isAllEmpty(addExitList)){
            exitStoreService.saveBatch(addExitList);

        }
        return MessageUtil.createMessage(true,"库存盘点成功");
    }

    @ResponseBody
    @RequestMapping("/update")
    Message update(@RequestParam("ids") Integer[] ids,@RequestParam("nums")Integer[] nums) {
        if(ids.length == 0 || nums.length == 0 || ids.length != nums.length){
            return MessageUtil.createMessage(false,"请完善信息");
        }
        Integer inventoryId = 0;
        for (int i=0;i<ids.length;i++) {
            InventoryReport inventoryReport = inventoryReportService.getById(ids[i]);
            // 生成报表
            inventoryId = inventoryReport.getInventoryId();
            inventoryReport.setPeopleNum(nums[i]);
            inventoryReportService.updateById(inventoryReport);

        }
        Inventory inventory = inventoryService.getById(inventoryId);
        if(!EmptyUtils.isEmpty(inventory)){
            inventory.setStatus(1);
            inventoryService.updateById(inventory);
        }
        return MessageUtil.createMessage(true,"修改");
    }

    @ResponseBody
    @RequestMapping("/review")
    Message review(@RequestParam("id")Integer id, @RequestParam(value = "verifierOpinion",required = false)String verifierOpinion, @RequestParam(value = "managersOpinion",required = false)String managersOpinion, @RequestParam("flag")Boolean flag) {
        Inventory result = inventoryService.getById(id);
        if(result.getStatus() == 1){
            result.setVerifierOpinion(verifierOpinion);
            if(!flag){
                result.setStatus(4);
                return MessageUtil.createMessage(true,"审核驳回成功");
            }
            result.setStatus(2);
            inventoryService.updateById(result);
            return MessageUtil.createMessage(true,"校验员审核通过");
        }else if(result.getStatus() == 2){
            result.setManagersOpinion(managersOpinion);
            if(!flag){
                result.setStatus(4);
                return MessageUtil.createMessage(true,"审核驳回成功");
            }
            result.setStatus(3);
            inventoryService.updateById(result);
            // 经理审核通过后 所有入库出库操作自动完成
            List<EnterStore> enterStoreList = enterStoreService.list(new LambdaQueryWrapper<EnterStore>().eq(EnterStore::getInventoryId,id));
            List<ExitStore> exitStoreList = exitStoreService.list(new LambdaQueryWrapper<ExitStore>().eq(ExitStore::getInventoryId,id));
            if(!EmptyUtils.isAllEmpty(enterStoreList)){
                for (EnterStore enterStore : enterStoreList) {
                    enterStore.setStatus(3);
                    Parts parts = partsService.getById(enterStore.getPartsId());
                    parts.setNum(parts.getNum()+enterStore.getNum());
                    partsService.updateById(parts);
                }
            }
            if(!EmptyUtils.isAllEmpty(exitStoreList)){
                for (ExitStore exitStore : exitStoreList) {
                    exitStore.setStatus(3);
                    Parts parts = partsService.getById(exitStore.getPartsId());
                    parts.setNum(parts.getNum()-exitStore.getNum());
                    partsService.updateById(parts);
                }
            }
            return MessageUtil.createMessage(true,"经理审核通过");
        }else {
            return MessageUtil.createMessage(false,"非审核状态无法审核");
        }
    }

}
